<template>
  <e-container :loading="loading">
    <e-title :title="action === 'edit' ? 'Edit Contact' : 'Add Contact'" />
    <a-divider />
    <div class="form">
      <a-form ref="formInstance" :model="apiData" layout="vertical" :rules="rules">
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Name" name="contactName">
              <a-tooltip
                :visible="nameIsExist.exits"
                placement="left"
                :get-popup-container="triggerNode => triggerNode.parentNode"
              >
                <template #title> Already have a contact named {{ nameIsExist.name }} </template>
                <a-input v-model:value="apiData.contactName" @blur="checkNameExist" />
              </a-tooltip>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Gender" name="gender">
              <a-select v-model:value="apiData.gender" :get-popup-container="triggerNode => triggerNode.parentNode">
                <a-select-option v-for="item in dict.genders" :key="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Type" name="contactType">
              <a-select
                v-model:value="apiData.contactType"
                :get-popup-container="triggerNode => triggerNode.parentNode"
              >
                <a-select-option v-for="item in dict.contactTypes" :key="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="E-mail" name="email">
              <a-input v-model:value="apiData.email" @blur="() => (apiData.email = apiData.email.trim())" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Department" name="department">
              <a-input v-model:value="apiData.department" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Country/Region" name="countryID">
              <e-country-region-select v-model="countryIDWrapped" :allow-clear="true" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Mobile Phone" name="cellPhone">
              <a-input v-model:value="apiData.cellPhone" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Office phone" name="officePhone">
              <a-input v-model:value="apiData.officePhone" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Zip Code" name="postalCode">
              <a-input v-model:value="apiData.postalCode" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Title" name="title">
              <a-input v-model:value="apiData.title" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="City/State" name="city">
              <a-input v-model:value="apiData.city" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Preferred IM" name="im">
              <a-select
                v-model:value="imWrapped"
                allow-clear
                :get-popup-container="triggerNode => triggerNode.parentNode"
              >
                <a-select-option v-for="item in dict.IMTypes" :key="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Perferred IM's Account" name="imAccount">
              <a-input v-model:value="apiData.imAccount" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Hobbies" name="hobbies">
              <a-input v-model:value="apiData.hobbies" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Personality" name="personality">
              <a-input v-model:value="apiData.personality" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Address" name="address">
              <a-input v-model:value="apiData.address" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Remark" name="comment">
              <a-textarea v-model:value="apiData.comment" :auto-size="{ minRows: 4, maxRows: 4 }" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-divider />
    <div class="buttons">
      <a-space size="middle">
        <a-button @click="handleContactCancel">Cancel</a-button>
        <a-button
          v-permission="action === 'edit' ? 'Contact:Edit' : 'Contact:Add'"
          type="primary"
          @click="handleContactSave"
          >Save</a-button
        >
      </a-space>
    </div>
  </e-container>
</template>

<script setup>
import { computed, inject, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import EContainer from '@/components/EContainer.vue'
import ETitle from '@/components/ETitle.vue'
import ECountryRegionSelect from '@/components/ECountryRegionSelect.vue'
import { useContactInfo } from '@/pages/Client/hooks/useContactInfo.js'
import { useDictNullValue } from '@/hooks/useDictNullValue.js'
import Contact from '@/api/client/contact.js'
import {
  CHECK_FORM_INTEGRITY,
  CONFIRM_BACK_TO_DETAIL,
  CONTACT_CREATED_SUCCESS,
  CONTACT_UPDATE_SUCCESS
} from '@/constants/message.js'
import { useRules } from '@/pages/Client/contact/useRules.js'
const { Modal, message } = inject('Feedback')

const props = defineProps({
  referenced: {
    type: Boolean,
    default: false
  },
  params: {
    type: Object,
    default() {
      return {}
    }
  }
})
const route = useRoute()
const router = useRouter()
const loading = ref(true)
const gutter = [120, 16]
// 组件被外部引用则通过道具取参数，正常通过路由取参数
const { id, action, contactId } = props.referenced ? props.params : route.params
const formInstance = ref(null)
const rules = useRules(id, contactId)
const apiData = reactive({
  contactName: '',
  gender: 0,
  title: '',
  email: '',
  contactType: 1,
  officePhone: '',
  cellPhone: '',
  department: '',
  countryID: 0,
  city: '',
  im: 0,
  imAccount: '',
  hobbies: '',
  postalCode: '',
  personality: '',
  address: '',
  comment: ''
})
const countryIDWrapped = useDictNullValue(apiData, 'countryID')
const imWrapped = useDictNullValue(apiData, 'im')
const store = useStore()
const dict = ref(computed(() => store.state.dict))
if (action === 'edit') {
  new Promise(resolve => {
    useContactInfo(contactId, resolve, true)
  }).then(contactInfo => {
    loading.value = false
    Object.keys(apiData).forEach(key => {
      apiData[key] = contactInfo.raw.value[key]
    })
  })
}
if (action === 'create') {
  loading.value = false
  document.title = 'Add Contact'
  store.dispatch('dict/getContactTypes')
  store.dispatch('dict/getIMTypes')
}
const emits = defineEmits(['cancel', 'updated'])
const handleContactCancel = () => {
  Modal.confirm({
    content: CONFIRM_BACK_TO_DETAIL,
    okButtonProps: { danger: true },
    onOk: () => {
      props.referenced ? emits('cancel') : router.back()
    }
  })
}
const handleContactSave = () => {
  formInstance.value
    .validate()
    .then(() => {
      loading.value = true
      if (action === 'edit') {
        apiData.id = contactId
        Contact.update(apiData)
          .then(() => {
            message.success(CONTACT_UPDATE_SUCCESS)
            emits('updated')
            if (window.location.hash === '#auto-close') window.close()
            if (!props.referenced) router.back()
          })
          .finally(() => {
            loading.value = false
          })
      }
      if (action === 'create') {
        apiData.clientOrgID = id
        Contact.add(apiData)
          .then(() => {
            message.success(CONTACT_CREATED_SUCCESS)
            emits('updated')
            if (!props.referenced) router.back()
          })
          .finally(() => {
            loading.value = false
          })
      }
    })
    .catch(() => {
      message.error(CHECK_FORM_INTEGRITY)
    })
}
const nameIsExist = ref({
  exits: false,
  name: ''
})
const checkNameExist = () => {
  Contact.isUniqueContactNameInThisClient(apiData.contactName, id, contactId).then(res => {
    if (res.data) {
      nameIsExist.value.exits = true
      nameIsExist.value.name = apiData.contactName
    } else {
      nameIsExist.value.exits = false
    }
  })
}
</script>

<style lang="less" scoped>
.form {
  padding: 0 228px;
}
.buttons {
  text-align: center;
}
</style>
<route lang="yaml">
name: Contact Edit
path: '/client/:id/contact/:action/:contactId?'
meta:
  sort: 1
  title: Contact Edit
  permission: Contact
</route>
